/**
 * 
 */
package com.hsxc.cdz.controller.consoleController;

import java.awt.FontFormatException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsxc.cdz.base.bean.ConsoleUser;
import com.hsxc.cdz.base.util.CheckMessage;
import com.hsxc.cdz.base.util.Constants;
import com.hsxc.cdz.base.util.GetRandnum;
import com.hsxc.cdz.mgmt.user.UserManager;

import net.sf.json.JSONObject;

/**
 * @author wpfei
 *
 */
@Controller
@RequestMapping("/api")
public class ConUserController {
	protected static Logger logger = Logger.getLogger(ConUserController.class);
	// ==============================================================================================================
	@Autowired
    UserManager usermanger;
	// =============================================================================================================
	// 类私有常量
	private static final int SUCCESS = 0;
	private static final int ERR_DATA = 1;
	private static final int ERR_DEVICE = 2;
	private static final int FAILURE = 3;

	// ============================================================================================================
	@RequestMapping(value = "/conuser", method = RequestMethod.POST)
	@ResponseBody
	// 增加用户
	public Object addusers(@RequestBody String params, HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, HttpSession httpSession) {

		Subject user = (Subject) httpSession.getAttribute("user");
		ConsoleUser consoleuser = new ConsoleUser();
		ConsoleUser parentuser = new ConsoleUser();
		JSONObject result = new JSONObject();
		parentuser = (ConsoleUser) httpSession.getAttribute("conuser");
		result.put("success", true);
		org.json.JSONObject jsonObject;
		try {
			jsonObject = new org.json.JSONObject(params);
			logger.info("输入参数" + params);
			consoleuser.setSsid(parentuser.getId());
			logger.info("用户ID" + parentuser.getId());
			if (user.hasRole("vendor") && jsonObject.getString("role").equals("operator")) {
				String randNum = GetRandnum.genRandomNum(4);
				while (usermanger.findOperatorByNo(randNum) != null) {
					logger.info("生成随机数");
					randNum = GetRandnum.genRandomNum(4);
				}
				consoleuser.setOperatorNO(randNum);
			}

			if (jsonObject.has("userName")) {
				logger.info("username" + jsonObject.getString("userName").trim());
				String userName = jsonObject.getString("userName");
				logger.info("运行到步骤1");
				logger.info(usermanger.loadConUserByName(userName));
				logger.info("运行到步骤2");
				if (usermanger.loadConUserByName(userName) != null) {
					throw new FontFormatException("该用户已经被注册");
				} else {
					logger.error("用户姓名为" + userName);
					consoleuser.setUser_name(userName);
				}
			}
			if (jsonObject.has("password")) {
				logger.error("password" + jsonObject.getString("password").trim());
				consoleuser.setPassword(jsonObject.getString("password").trim());
			}
			if (jsonObject.has("role")) {
				logger.error("role" + jsonObject.getString("role"));
				consoleuser.setRole(jsonObject.getString("role").trim());
			}
			if (jsonObject.has("email")) {
				logger.error("email" + jsonObject.getString("email").trim());
				String email = jsonObject.getString("email");
				if (CheckMessage.isEmail(email)) {
					consoleuser.setEmail(jsonObject.getString("email").trim());
				} else {
					throw new FontFormatException("邮箱格式错误");
				}
			}
			if (jsonObject.has("mobile")) {
				logger.error("mobile" + jsonObject.getString("mobile"));
				String tel = jsonObject.getString("mobile");
				if (CheckMessage.isPhone(tel) && (!(usermanger.loadConUserByMobile(tel) != null))) {
					consoleuser.setMobile(jsonObject.getString("mobile"));
				} else {
					if (usermanger.loadConUserByMobile(tel) != null) {
						throw new FontFormatException("该手机号码已经被注册");
					} else {
						throw new FontFormatException("手机号码格式错误");
					}
				}

			}
			if (jsonObject.has("company")) {
				logger.info("company" + jsonObject.getString("company").trim());
				consoleuser.setCompany(jsonObject.getString("company").trim());
			}
			if (jsonObject.has("idNumber")) {
				logger.info("idnumber is " + jsonObject.getString("idNumber").trim());
				String IDStr = jsonObject.getString("idNumber");
				if (CheckMessage.IDCardValidate(IDStr).equals("")) {
					consoleuser.setId_number(jsonObject.getString("idNumber").trim());
				} else {
					throw new FontFormatException("该身份证号码格式错误");
				}

			}
			if (jsonObject.has("address")) {
				logger.info("address" + jsonObject.getString("address").trim());
				consoleuser.setAddress(jsonObject.getString("address").trim());
			}
			if (jsonObject.has("describle")) {
				logger.info("describle" + jsonObject.getString("describle").trim());
				consoleuser.setDescrible(jsonObject.getString("describle").trim());
			}

		} catch (FontFormatException e) {
			result.put("added", false);
			result.put("message", "数据格式有误:" + e.getMessage());
			logger.info("数据格式有误:" + e.getMessage());
			return result;
		} catch (Exception e) {
			result.put("added", false);
			result.put("message", "用户注册异常");
			logger.info("用户注册异常");
			return result;
		}

		if ((usermanger.insertConUser(consoleuser) < 0)) {
			result.put("added", false);
			result.put("message", "用户注册失败");
			logger.info("用户注册失败");
		} else {
			result.put("added", true);
			result.put("message", "用户注册成功");
			logger.info("用户注册成功");
		}
		return result;
	}

	// ==============================================================================================================
	@RequestMapping(value = "/conuser", method = RequestMethod.GET)
	@ResponseBody
	// 获取用户信息
	public Object getusers(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			HttpSession httpSession) {

		logger.info("进入GET方法查找用户");
		Subject user = (Subject) httpSession.getAttribute("user");
		ConsoleUser consoleUser = (ConsoleUser) httpSession.getAttribute("conuser");
		logger.info("username: " + user.getPrincipal().toString());
		Session ses = user.getSession();
		logger.info("session id: " + ses.getId().toString());
		String userID = (String) user.getPrincipal();
		logger.info("USERid" + userID);
		JSONObject result = new JSONObject();
		List<ConsoleUser> users = null;
		try {
			if (user.hasRole(consoleUser.getRole())) {
				logger.info("授权成功");
				users = usermanger.findConUserByRole(consoleUser);
			} else {
				logger.info("输出user" + "授权不成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("数据库查找失败");
		}
		result.put("success", true);
		result.put("data", users);
		return result;
	}

	@RequestMapping(value = "/conuser/{userID}", method = RequestMethod.DELETE)
	@ResponseBody
	// 删除用户
	public Object deleteusers(@PathVariable("userID") int userID) {
		// org.json.JSONObject ;
		JSONObject result = new JSONObject();

		result.put("success", true);
		try {

			usermanger.deleteConUser(userID);
			result.put("added", true);
		} catch (Exception e) {
			result.put("added", false);
			result.put("message", "用户删除失败");
		}

		return result;
	}

	// ===================================================================================================================
	@RequestMapping(value = "/conuser", method = RequestMethod.PUT)
	@ResponseBody
	// 更新用户信息
	public Object putusers(@RequestBody String params, HttpSession httpSession) {
		org.json.JSONObject json = null;
		JSONObject result = new JSONObject();
		try {
			json = new org.json.JSONObject(params);
			result.put("success", true);
		} catch (JSONException e) {
			e.printStackTrace();
			result.put("success", false);
			return result;
		}
		logger.info("收到的数据" + params);
		ConsoleUser consoleuser = new ConsoleUser();
		ConsoleUser currentUser = (ConsoleUser) httpSession.getAttribute("conuser");
		try {
			if (json.has("password"))
				consoleuser.setPassword(json.getString("password"));
			if (json.has("role"))
				consoleuser.setRole(json.getString("role"));
			if (json.has("email"))
				consoleuser.setEmail(json.getString("email"));
			if (json.has("mobile"))
				consoleuser.setMobile(json.getString("mobile"));
			if (json.has("company"))
				consoleuser.setCompany(json.getString("company"));
			if (json.has("id"))
				consoleuser.setId_number(json.getInt("id") + "");
			if (json.has("address"))
				consoleuser.setAddress(json.getString("address"));
			if (json.has("describle"))
				consoleuser.setDescrible(json.getString("describle"));
			consoleuser.setUser_name(currentUser.getUser_name());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		if (usermanger.updateConUser(consoleuser) >= 0) {
			result.put("added", true);
			consoleuser = usermanger.loadConUserByName(consoleuser.getUser_name());
			result.put("userInfo", consoleuser);
			httpSession.setAttribute("conuser", consoleuser);
		} else {
			result.put("added", false);
		}
		return result;
		// return log;

	}

	// ==================================================================================================================
	@RequestMapping(value = "/lockuser", method = RequestMethod.POST)
	@ResponseBody
	public Object lockuser(@RequestBody String params) {
		org.json.JSONObject json = null;
		JSONObject result = new JSONObject();
		try {
			json = new org.json.JSONObject(params);
			result.put("success", true);
		} catch (JSONException e) {
			e.printStackTrace();
			result.put("success", false);
			return result;
		}
		logger.info("收到的数据" + params);
		ConsoleUser consoleuser = new ConsoleUser();
		try {
			if (json.has("id")) {
				consoleuser.setId(json.getInt("id"));
				logger.info("===================" + "id:" + json.getInt("id") + "======================");
			}
			consoleuser.setState(Constants.USER_LOCK);

		} catch (JSONException e) {
			e.printStackTrace();

		}

		if (usermanger.lockAccount(consoleuser) >= 0) {
			result.put("added", true);
			result.put("errcode", SUCCESS);

		} else {
			result.put("added", false);
			result.put("errcode", FAILURE);
		}
		return result;

	}

	// ==============================================================================================================
	@RequestMapping(value = "/unlockuser", method = RequestMethod.POST)
	@ResponseBody
	public Object unlockuser(@RequestBody String params) {
		org.json.JSONObject json = null;
		JSONObject result = new JSONObject();
		try {
			json = new org.json.JSONObject(params);
			result.put("success", true);
		} catch (JSONException e) {
			e.printStackTrace();
			result.put("success", false);
			return result;
		}
		logger.info("收到的数据" + params);
		ConsoleUser consoleuser = new ConsoleUser();
		try {
			if (json.has("id")) {
				consoleuser.setId(json.getInt("id"));
			}
			consoleuser.setState(Constants.USER_UNLCK);
		} catch (JSONException e) {
			e.printStackTrace();

		}
		if (usermanger.lockAccount(consoleuser) >= 0) {
			result.put("added", true);
			result.put("errcode", SUCCESS);
		} else {
			result.put("added", false);
			result.put("errcode", FAILURE);
		}
		return result;
	}
}
